﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;

namespace mitasoft.AdsShedule.Infrastructure
{
    public static class ErrorCheck
    {
        public static void DoCheck(Action toExecute)
        {
            try
            {
                toExecute();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                Thread tr = new Thread(new ParameterizedThreadStart(TryToSendEmail));
                tr.Start(ex);
                
                //TryToSendEmail(ex);
            }
        }
        private static void TryToSendEmail(object ex)
        {
            try
            {
                WebRequest request = WebRequest.Create("http://www.google.com");
                request.GetResponse();
                SendEmail((Exception)ex);
            }
            catch
            {

            }
        }
        private static void SendEmail(Exception ex)
        {
            string emailAddress = "mitasoft.app@gmail.com";
            string emailPassword = "htchero!@#";

            StringBuilder messageBuilder = new StringBuilder();
            messageBuilder.AppendLine("Exception message");
            messageBuilder.AppendLine(ex.Message);
            messageBuilder.AppendLine();
            messageBuilder.AppendLine("Exception stacktrace");
            messageBuilder.AppendLine(ex.StackTrace);
            messageBuilder.AppendLine();
            messageBuilder.AppendLine("Exception inner message");
            messageBuilder.AppendLine();
            messageBuilder.AppendLine(ex.InnerException != null && ex.InnerException != null ? ex.InnerException.Message : "No inner exception");
            messageBuilder.AppendLine("Exception inner stack");
            messageBuilder.AppendLine();
            messageBuilder.AppendLine(ex.InnerException != null ? ex.InnerException.StackTrace : "No inner stack trace");

            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(emailAddress, emailAddress);
            message.Subject = string.Format("{0} - {1} - {2}", DateTime.Now.ToString(), "RVE Ads", ex.Message);
            message.Body = messageBuilder.ToString();

            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential(emailAddress, emailPassword);
            client.SendAsync(message, null);
        }
    }
}
